#-*-coding:utf-8 -*-
from flask import Flask,Blueprint,render_template
from flask import request
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# 链接数据库
class Config(object):
    SQLALCHEMY_DATABASE_URI = 'mysql://root:mysql@127.0.0.1:3306/liuyanflask'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = True

app.config.from_object(Config)

# 创建oem对象
db = SQLAlchemy(app)

# 创建表
# class Users(db.Model):
#     """
#     新闻频道
#     """
#     __tablename__ = 'users'
#
#     id = db.Column(db.Integer, primary_key=True, doc='用户id')
#     name = db.Column(db.String(20), doc='用户名')
#     ctime = db.Column(db.DateTime, default=datetime.now, doc='创建时间')
#     utime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, doc='更新时间')
class MessageBoard(db.Model):
    """
    新闻频道
    """
    __tablename__ = 'messageboard'
    id= db.Column(db.Integer, primary_key=True, doc='用户id')
    # user_id = db.Column(db.Integer, db.ForeignKey('users.id'), doc='用户id')
    user_name = db.Column(db.String(20), doc='用户名')
    email = db.Column(db.String(20), doc='邮箱')
    content = db.Column(db.String(500), doc='内容')
    type = db.Column(db.String(20), doc='类型')
    ctime = db.Column(db.DateTime, default=datetime.now, doc='创建时间')
    utime = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, doc='更新时间')

# 1、定义蓝图：
user_db = Blueprint('user',__name__)#第一个参数为子应用的名称
#2、定义蓝图路由
@user_db.route('/',methods=['POST', 'GET'])
def index3():
    if request.method =="GET":
        messageboard = db.session.query(MessageBoard).order_by(MessageBoard.id.desc()).all()
        a = "1"
        print(messageboard)
        for i in messageboard:
            print(i.user_name,i.content)


        return render_template("index.html",a=a,messageboard=messageboard)

    if request.method =="POST":
        name = request.form.get("name")
        email = request.form.get("email")
        message = request.form.get("message")
        selection = request.form.get("selection")
        print(selection)
        user = MessageBoard(user_name=name, email=email,content=message,type=selection)
        db.session.add(user)  # 生成sql语句
        db.session.commit()  # 执行sql语句
        return "留言成功 <a href='/'>返回留言</a>"

#3、注册应用
app.register_blueprint(user_db)#里面的参数为定义蓝图的对象，注册的时候可以通过url_prefix='/users'的方式设置子应用的前缀
#app.register_blueprint(user_db,url_prefix='/users')

if __name__ == '__main__':

    # # 删除表
    # db.drop_all()
    #
    # # 创建表
    # db.create_all()

    app.run()